import 'package:fluent_ui/fluent_ui.dart';

import '../../api/school_daily_schedule_api.dart';
import '../../components/data_table.dart';
import '../../model/school_daily_schedule_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';
import '../app/app_school_data.dart';

abstract class SchoolDailyScheduleField {}

///学校作息:查询字段
enum SchoolDailyScheduleQueryField implements SchoolDailyScheduleField {
  semester('学年学期'),
  segment('分段节次'),
  title('标题'),
  status('状态');

  final String label;

  const SchoolDailyScheduleQueryField(this.label);
}

///学校作息:输入字段
enum SchoolDailyScheduleInputField implements SchoolDailyScheduleField {
  title('标题', checked: true),
  semester('学年学期', checked: true),
  segment('分段节次', checked: true),
  startTime('开始时间', checked: true),
  endTime('结束时间', checked: true),
  remark('备注'),
  status('状态', isAdd: false);

  final String label;
  final bool checked, isAdd;

  const SchoolDailyScheduleInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler<T>(final T? val) {
    if (checked) {
      if (val == null) {
        return '$label不能为空';
      }
      if (val is String) {
        return val.isEmpty ? '$label不能为空' : null;
      }
      if (val is List) {
        return val.isEmpty ? '$label不能为空' : null;
      }
    }
    return null;
  }
}

///学校作息:视图模型
class SchoolDailyScheduleViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <SchoolDailyScheduleQueryField, TextEditingController>{
    for (var field in SchoolDailyScheduleQueryField.values)
      field: TextEditingController(),
  };

  //输入字段
  final _inputFields = <SchoolDailyScheduleInputField, TextEditingController>{
    for (var field in SchoolDailyScheduleInputField.values)
      field: TextEditingController(),
  };

  //获取控制器
  TextEditingController? getController<T extends SchoolDailyScheduleField>(
      final T field) {
    //查询字段
    if (field is SchoolDailyScheduleQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is SchoolDailyScheduleInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends SchoolDailyScheduleField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends SchoolDailyScheduleField>(T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];
  final _schoolSemesters = <String, List<ComboBoxItem<String>>>{};

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///获取学校学年学期选项集合
  List<ComboBoxItem<String>> semestersBySchool(final String? schoolId) =>
      _schoolSemesters[schoolId ?? ''] ?? [];

  ///加载字典
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then(
        (opts) {
          if (opts.isNotEmpty) {
            _statusOpts.addAll(opts);
          }
        },
      );
      futures.add(future);
    }
  }

  ///加载学校学年学期
  void _loadSemesters(String? schoolId, List<Future<dynamic>> futures) {
    if (schoolId == null || schoolId.isEmpty) {
      return;
    }
    //加载学校学年学期
    final future = appSchoolData
        .buildSemesterOpts(schoolId)
        .then((opts) => _schoolSemesters[schoolId] = opts);
    //添加到列表
    futures.add(future);
  }

  ///加载数据
  void loadInit(final String? schoolId) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //加载学校学年学期
    _loadSemesters(schoolId, futures);
    //请求同步
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      notifyListeners();
    }
  }

  ///清空查询字段
  void cleanQueryFields() {
    for (var ctl in _queryFields.values) {
      ctl.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var ctl in _inputFields.values) {
      ctl.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SchoolDailyScheduleItemRes>();

  ///分页查询
  void query(final String? schoolId) async {
    if (schoolId == null || schoolId.isEmpty) {
      return;
    }
    try {
      loading.showLoading();
      //查询条件
      final status = getFieldValue(SchoolDailyScheduleQueryField.status);
      final segment = getFieldValue(SchoolDailyScheduleQueryField.segment);
      final req = SchoolDailyScheduleQueryReq(
        schoolId: schoolId,
        semesterId: getFieldValue(SchoolDailyScheduleQueryField.semester) ?? '',
        segment: int.tryParse(segment ?? '') ?? -1,
        title: getFieldValue(SchoolDailyScheduleQueryField.title) ?? '',
        status: int.tryParse(status ?? '') ?? -1,
      );
      final res = await schoolDailyScheduleApi.query(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint('schoolDailyScheduleApi.query(req:${req.toMap()})=>$res');
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById({required final String schoolId, id}) async {
    try {
      loading.showLoading();
      final futures = <Future<dynamic>>[];
      //加载字典
      _loadDict(futures);
      //加载学校学年学期
      _loadSemesters(schoolId, futures);
      //加载数据
      final future = schoolDailyScheduleApi.info(id).then((res) {
        if (res.isSuccessed) {
          setFieldValue(SchoolDailyScheduleInputField.title, res.title);
          setFieldValue(SchoolDailyScheduleInputField.remark, res.remark);
          setFieldValue(SchoolDailyScheduleInputField.semester, res.semesterId);
          setFieldValue(
            SchoolDailyScheduleInputField.segment,
            '${res.segment}',
          );
          setFieldValue(SchoolDailyScheduleInputField.startTime, res.startTime);
          setFieldValue(SchoolDailyScheduleInputField.endTime, res.endTime);
          setFieldValue(SchoolDailyScheduleInputField.status, '${res.status}');
          return;
        }
        final String err;
        if ((err = res.retMessage).isNotEmpty) {
          loading.showToast(err);
        }
      });
      futures.add(future);
      //请求同步
      if (futures.isNotEmpty) {
        await Future.wait(futures);
        notifyListeners();
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增处理
  void onAddHandler(final String schoolId, final VoidCallback handler) async {
    try {
      loading.showLoading();
      //新增处理
      final segment = getFieldValue(SchoolDailyScheduleInputField.segment);
      final req = SchoolDailyScheduleAddReq(
        schoolId: schoolId,
        title: getFieldValue(SchoolDailyScheduleInputField.title) ?? '',
        remark: getFieldValue(SchoolDailyScheduleInputField.remark) ?? '',
        semesterId: getFieldValue(SchoolDailyScheduleInputField.semester) ?? '',
        segment: int.tryParse(segment ?? '') ?? 1,
        startTime: getFieldValue(SchoolDailyScheduleInputField.startTime) ?? '',
        endTime: getFieldValue(SchoolDailyScheduleInputField.endTime) ?? '',
      );
      //提交
      final res = await schoolDailyScheduleApi.add(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      //修改处理
      final segment = getFieldValue(SchoolDailyScheduleInputField.segment);
      final status = getFieldValue(SchoolDailyScheduleInputField.status);
      final req = SchoolDailyScheduleModifyReq(
        id: id,
        title: getFieldValue(SchoolDailyScheduleInputField.title) ?? '',
        remark: getFieldValue(SchoolDailyScheduleInputField.remark) ?? '',
        semesterId: getFieldValue(SchoolDailyScheduleInputField.semester) ?? '',
        segment: int.tryParse(segment ?? '') ?? 1,
        startTime: getFieldValue(SchoolDailyScheduleInputField.startTime) ?? '',
        endTime: getFieldValue(SchoolDailyScheduleInputField.endTime) ?? '',
        status: int.tryParse(status ?? '') ?? 1,
      );
      //提交
      final res = await schoolDailyScheduleApi.modify(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler({required final String schoolId, id}) async {
    try {
      loading.showLoading();
      //删除
      final res = await schoolDailyScheduleApi.delete(id);
      if (res.isSuccessed) {
        query(schoolId);
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
